package com.example.demo.arithmetic.datastructure.stack;

/**
 * @Description: 数组模拟的栈实现
 * @Author: LLL
 * @Date: 2020-03-14 14:18
 **/
public class ArrayStack {

    /**
     * 栈容量
     */
    private int maxSize;

    /**
     * 数据
     */
    private int[] data;

    /**
     * 指向栈顶元素
     */
    private int top = -1;

    /**
     * @param maxSize 最大容量
     *                构造器
     */
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        data = new int[maxSize];
    }

    /**
     * @return true：满
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * @return 是否空
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * @param val 入栈值
     *            入栈
     */
    public void push(int val) {
        if (isFull()) {
            System.out.println("栈满！");
            return;
        }
        data[++top] = val;
    }

    /**
     * 出栈
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空");
        }
        //        int val = data[top];
        //        //        top --;
        return data[top--];
    }

    /**
     * @Description: 遍历
     * @Param: * @param
     * @return: void
     * @Author: liull
     * @Date: 2020/3/14
     */
    public void list() {
        if (isEmpty()) {
            System.out.println("无数据！");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", /*top -*/ i, data[i]);
        }
    }

    /** *********************************************** 计算表达式扩展的方法***********************************************/
    /**
     * @param oper 计算操作符优先级 数字越大优先级越高
     * @return
     */

    private static final char ADD = '+';

    private static final char SUB = '-';

    private static final char MUL = '*';

    private static final char DIV = '/';

    public int priority(int oper) {
        if (oper == MUL || oper == DIV) {
            return 1;
        } else if (oper == SUB || oper == ADD) {
            return 0;
        } else
            return -1;
    }

    /**
     * @param oper 操作符
     * @return 操作符是否合法
     */
    public boolean isOper(char oper) {
        return oper == ADD || oper == SUB || oper == MUL || oper == DIV;
    }

    public Integer calc(char operation, int op1, int op2) {

        int result = 0;

        switch (operation) {
            case ADD:
                result = op2 + op1;
                break;
            // 注意顺序
            case SUB:
                result = op2 - op1;
                break;
            case MUL:
                result = op2 * op1;
                break;
            case DIV:
                result = op2 / op1;
                break;
        }
        return result;
    }

    public int peek() {
        if (!isEmpty()) {
            return data[top];
        }
        return -1000;// 基本不会走到这
    }
}
